package org.brownflat.lighthouse.config;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Properties;

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
	
	private static final Logger LOG = Logger.getLogger(PropertyPlaceholder.class);
	private volatile String hostname;
    private volatile String propertiesLocation;
    private Properties defaultProperties;
    private Properties hostProperties;

    public PropertyPlaceholder(String propertiesLocation) {
        this.propertiesLocation = propertiesLocation;
		InetAddress localMachine;
		try {
			localMachine = InetAddress.getLocalHost();
			hostname = localMachine.getHostName();
			loadDefaultProperties();
            loadHostProperties();
		} catch (Exception e) {
			LOG.error(e);
		}

        if(defaultProperties == null && hostProperties == null) {
            throw new RuntimeException(String.format("No properties configuration available at %s", propertiesLocation));
        }
	}

	protected String resolvePlaceholder(String placeholder, Properties props) {		
    	String value = (hasHostProperties() && hostProperties.getProperty(placeholder) != null)
                ? hostProperties.getProperty(placeholder)
                : defaultProperties.getProperty(placeholder);
	    LOG.info(String.format("Loading property [%s] with [%s].", placeholder, value));
		return value;
	}

    private void loadDefaultProperties() throws IOException {
        InputStream resourceAsStream = this.getClass().getResourceAsStream(propertiesLocation + "lighthouse-default.properties");
        if(resourceAsStream != null) {
            LOG.info("Loading default configuration properties");
            defaultProperties = new Properties();
            defaultProperties.load(resourceAsStream);
        } else {
            throw new RuntimeException("Could not find default properties file");
        }
    }

    private void loadHostProperties() throws IOException {
        InputStream resourceAsStream = this.getClass().getResourceAsStream(propertiesLocation + hostname + ".properties");
        if(resourceAsStream != null) {
            LOG.info("Loading configuration properties for Host: " + hostname);
            hostProperties = new Properties();
            hostProperties.load(resourceAsStream);
        }
    }

    private boolean hasHostProperties() {
        return hostProperties != null;
    }
}
